import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:wechat/pages/chat/chat_model.dart';
import 'package:wechat/pages/chat/search_bar.dart';
import 'package:wechat/pages/const.dart';
import 'package:http/http.dart' as http;

class ChatPage extends StatefulWidget {
  const ChatPage({Key? key}) : super(key: key);

  @override
  State<ChatPage> createState() => _ChatPageState();
}
List<PopupMenuItem<String>> _buildPopMenuItem(BuildContext context) {
  return [
    _buildItem("发起群聊", "发起群聊"),
    _buildItem("添加朋友", "添加朋友"),
    _buildItem("扫一扫1", "扫一扫"),
    _buildItem("收付款", "收付款"),
  ];
}

PopupMenuItem<String> _buildItem(String imageName, String title) {
  return PopupMenuItem(
    child: Container(
      child: Row(
        children: [
          Image(image: AssetImage("images/chat/${imageName}.png"), width: 20,),
          SizedBox(width: 10,),
          Text(title, style: TextStyle(color: Colors.white),),
        ],
      ),
    ),
  );
}
class _ChatPageState extends State<ChatPage> with AutomaticKeepAliveClientMixin<ChatPage> {

  test() {
    final map = {
      "username" : "zhangsan",
      "message" : "吃饭了吗?",
      'imageUrl': "https://randomuser.me/api/portraits/lego/4.jpg"
    };
    //map转json字符串
    final jsonString = json.encode(map);
    print(jsonString);
    //json转map
    var map2 = json.decode(jsonString);
    print(map2);
    print(map2.runtimeType);
    print(map2['username']);
    print(map2['message']);
    print(map2['imageUrl']);

    //map转模型 bean
    ChatModel model = ChatModel.fromMap(map2);
    print(model.runtimeType);
    print(model.username);
    print(model.message);
    print(model.imageUrl);
    print(model);

  }
  List<ChatModel> _chatLists = [];
  bool _cancelConnect = false;
  @override
  void initState() {
    super.initState();
    // test();
    //网路请求
    //print("进行网络请求之前");
    //改为异步渲染了
    getDatas()?.then((value) {
      if (!_cancelConnect) {
        setState(() {
          _chatLists = value;
        });
      }
    }).catchError(
        (error) {
          print("exception:$error");
        }
    ).whenComplete(() {
      print("whenComplete");
    }).timeout(Duration(seconds: 15)).catchError(
        (timeoutError) {
          _cancelConnect = true;
          print("超时错误了：$timeoutError");
        }
    );
    //print("进行网络请求之后");
  }

  Future<List<ChatModel>>? getDatas() async {
    _cancelConnect = false;
    //print("开始请求");
    var url = Uri.http('rap2api.taobao.org', '/app/mock/307795/api/chatList');
    http.Response response = await http.get(url);
    print(response.statusCode);
    if (response.statusCode == 200) {
      //sleep(Duration(seconds: 2));
      //print("请求成功");
      var map = json.decode(response.body);
      List<ChatModel> datas = map['chat_list'].map<ChatModel>(
          (item) {
            return ChatModel.fromMap(item);
          }
      ).toList();
      return datas;
    }else {
      print("请求失败");
      throw Exception("statusCode:${response.statusCode}");
    }
  }
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        elevation: 0.0, //隐藏导航栏下面的线
        title: Text("微信", style: TextStyle(color: Colors.black),),
        centerTitle: true,
        backgroundColor: wechatThemeColor,
        actions: [
          Container(
            padding: EdgeInsets.only(right: 10),
            child: PopupMenuButton(
              color: Color.fromRGBO(0, 0, 0, 0.8),
              offset: Offset(0, 50),
              child: Image(image: AssetImage("images/chat/圆加.png"), width: 30,),
              itemBuilder: _buildPopMenuItem,
            ),
          ),
        ],
      ),
      body: Container(
        child: _chatLists.length == 0 ? Center(
          child: Text("加载中..."),
        ) : ListView.builder(
            itemBuilder: _buildItemForRow,
          itemCount: _chatLists.length+1,
        ),
      ),
    );
  }

  Widget _buildItemForRow(BuildContext context, int index) {
    if (index == 0) {
      return SearchBar(datas: _chatLists);
    }
    return ListTile(
      title: Text(_chatLists[index-1].username),
      subtitle: Container(
        width: 20,
        height: 20,
        child: Text(_chatLists[index-1].message, overflow: TextOverflow.ellipsis,),
      ),
      leading: CircleAvatar(
        backgroundImage: NetworkImage(_chatLists[index-1].imageUrl),
      ),
    );
  }
  //Mixin保存状态的
  @override
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    super.dispose();
    print("聊天界面销毁了");
  }
}
/**
 * Mixin混入
 * 1.with AutomaticKeepAliveClientMixin<ChatPage>
 *   协议是当前类，与state写法一致
 * 2.重写 wantKeepAlive 返回true
 * 3.build方法中，调用父类的build方法
 *   super.build(context);
 */
/*
body: FutureBuilder(
        future: getDatas(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          //print("异步渲染：${snapshot.data}");
          if (snapshot.connectionState == ConnectionState.none) {
            return Center(
              child: Text("加载失败"),
            );
          }else if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(
              child: Text("加载中..."),
            );
          }else {
            return ListView(
              children: snapshot.data.map<Widget>(
                  (ChatModel item) {
                    return ListTile(
                      title: Text(item.username),
                      subtitle: Container(
                        width: 20,
                        height: 20,
                        child: Text(item.message, overflow: TextOverflow.ellipsis,),
                      ),
                      leading: CircleAvatar(
                        backgroundImage: NetworkImage(item.imageUrl),
                      ),
                    );
                  }
              ).toList(),
            );
          }
        },
      ), //异步渲染的
 */